<template>
    <div>
        <el-form-item label="交互类型" :prop="props.mutual" :rules="rules.mutual">
            <el-tree-select
                v-model="state.mutual"
                :data="props.typeList"
                :render-after-expand="false"
                :props="defaultProps"
                placeholder="请选择交互类型"
                @change="change"
                :disabled="props.isHomePage === 1" />
        </el-form-item>
        <el-form-item label="跳转页面" v-if="state.mutual == 12" :prop="props.url" :rules="rules.url">
            <el-input v-model="state.url" @blur="getUrl" placeholder="请输入页面路径"></el-input>
            <div class="tips">请确保小程序页面路径可访问，例如： /pages/home/index?pageId=1001</div>
        </el-form-item>
        <el-form-item label="跳转页面" v-else-if="state.mutual == 4" :prop="props.id" :rules="rules.id">
            <el-select v-model="state.id" reserve-keyword placeholder="请选择目标分组" @change="selectGroup">
                <el-option v-for="item in props.category" :key="item.id" :label="item.categoryName" :value="item.id" />
            </el-select>
        </el-form-item>
        <div v-else-if="state.mutual == 14">
            <el-form-item label="跳转页面" :prop="props.appId" :rules="rules.appId">
                <el-input v-model="state.appId" @blur="getUrl" placeholder="请输入小程序AppID"></el-input>
            </el-form-item>
            <el-form-item class="label_hide" label=" " :prop="props.url" :rules="rules.url">
                <el-input v-model="state.url" @blur="getUrl" placeholder="请输入页面路径"></el-input>
                <div class="tips">请确保小程序页面路径可访问，例如： /pages/home/index?pageId=1001</div>
            </el-form-item>
        </div>
        <div v-else-if="state.mutual == 19">
            <el-form-item label="跳转页面" :prop="props.openimg" :rules="rules.openimg">
                <ImgUpload :limit="0" @imgStateChange="imgChangeHandler" :currentImg="state.openimg" />
            </el-form-item>
        </div>
        <el-form-item label="跳转页面" v-else :prop="props.url" :rules="rules.url">
            <template v-if="props.isHomePage === 1">
                <el-input v-model="state.chooseName" disabled></el-input>
            </template>
            <template v-else>
                <el-input v-model="state.page" v-if="[1, 5, '', 13, 18, 7].includes(state.mutual)" disabled></el-input>
                <div
                    v-if="![1, 5, '', 7, 13, 18, 11].includes(state.mutual)"
                    @click="openDialog"
                    class="btnText-hidden">
                    {{ state.chooseName ? state.chooseName : `选择${state.page}` }}
                </div>
                <!-- 满减活动 -->
                <div v-if="state.mutual == 11">
                    <ZwChooseEnough :value="state" @handle-confirm="getSelected($event, index)">
                        <template #btn>
                            <div class="btnText-hidden">
                                {{ state.chooseName ? state.chooseName : `选择${state.page}` }}
                            </div>
                        </template>
                    </ZwChooseEnough>
                </div>
            </template>
        </el-form-item>
        <!-- 微页面 -->
        <div v-if="open">
            <PageChoose :open="open" :id="id" @cancel="cancel" @submit="submit" ref="pageRef" />
        </div>
        <!-- 优惠券 -->
        <!-- <div v-if="couponOpen">
            <CouponList :open="couponOpen" :id="id" @cancel="couponCancel" @submit="couponSubmit" ref="couponRef" />
        </div> -->
        <ZwChooseCoupon
            :shopId="shopId"
            :value="id"
            @handle-confirm="couponSubmit"
            :btnVisible="false"
            ref="couponRef" />
        <!-- 秒杀活动 -->
        <ZwSeckillActivity ref="ZwSeckillActivityRef" @submit="getSeckill" :multiple="false" />
        <!-- 拼团活动 -->
        <ZwGroupActivity ref="ZwGroupActivityRef" @submit="getGroup" :multiple="false" />
        <!-- 抽奖活动 -->
        <ZwLotteryActivity ref="ZwLotteryActivityRef" @submit="getLottery" />
        <!-- 选择商品 -->
        <ZwGeneralGoods :value="goodsId" @handle-confirm="goodssubmit" ref="goodsRef" :btnVisible="false">
        </ZwGeneralGoods>
    </div>
</template>
<script setup>
import { ref, reactive, watch } from 'vue';
import { ElMessage, selectGroupKey } from 'element-plus';
import storage from '@/commons/storage';
import constants from '@/commons/constants';
import PageChoose from '@/components/PageChoose.vue';
import CouponList from '@/components/CouponList.vue';
import ImgUpload from '@/components/ImgUpload.vue';
import { isNotEmpty } from '@/commons/utils';

let shopId = ref(storage.get('ZW-SHOPID'));

const props = defineProps({
    typeList: { type: Array, default: () => [] },
    category: { type: Array, default: () => [] },
    row: { type: Object, default: () => ({}) },
    mutual: { type: String, default: 'mutual' },
    url: { type: String, default: 'url' },
    id: { type: String, default: 'id' },
    appId: { type: String, default: 'appId' },
    openimg: { type: String, default: 'openimg' },
    isHomePage: { type: Number, default: 0 }
});
const defaultProps = {
    children: 'children',
    label: 'lable'
};
const emit = defineEmits(['sendParam']);
const goodsRef = ref();
const couponRef = ref();
const pageRef = ref();
const open = ref();
const couponOpen = ref();
const ZwGroupActivityRef = ref();
const ZwSeckillActivityRef = ref();
const ZwLotteryActivityRef = ref();
const id = ref();
let rowId = ref();
const goodsId = ref();
let state = reactive({ mutual: '', page: '', id: '', chooseName: '', url: '', appId: '', openimg: '' });
const rules = reactive({
    mutual: [{ required: true, message: '交互类型不能为空', trigger: 'change' }],
    url: [{ required: true, message: '导航路径不能为空', trigger: 'blur' }],
    appId: [{ required: true, message: 'AppID不能为空', trigger: 'blur' }],
    openimg: [{ required: true, message: '打开图片不能为空', trigger: 'change' }],
    id: [{ required: true, message: '请选择目标分组', trigger: 'change' }]
});
const mutualType = reactive({
    1: '/pages/tabbar/cart',
    2: '/pages-activity/dynamic/index?id=',
    3: '/pages-cart/good/index?goodsId=',
    4: '/pages/tabbar/category',
    5: '/pages/tabbar/user',
    6: '/pages-user/coupon/receive?couponId=',
    7: '',
    8: '/pages-cart/good/index?source=2&goodsId=',
    9: '/pages-cart/good/index?goodsId=',
    10: '/pages-cart/luckDraw/index?luckDrawId=',
    11: '/pages-cart/activeDetail/index?activityId=',
    13: '/pages/tabbar/home',
    18: '/pages-user/myIntegral/shoppingMall'
});
const openDialog = () => {
    let param = JSON.parse(JSON.stringify(state));
    if (state.mutual == 2) {
        //微页面
        id.value = state.id;
        open.value = true;
    } else if (state.mutual == 3) {
        //商品页
        goodsId.value = state.id;
        goodsRef.value.handleVisible(true);
    } else if (state.mutual == 6) {
        //优惠券
        id.value = state.id;
        // couponOpen.value = true;
        couponRef.value.handleVisible(true);
    } else if (state.mutual == 8) {
        //拼团
        ZwGroupActivityRef.value.onOpen(Object.assign(param, { id: rowId.value }));
    } else if (state.mutual == 9) {
        //秒杀
        ZwSeckillActivityRef.value.onOpen(Object.assign(param, { id: rowId.value }));
    } else if (state.mutual == 10) {
        //抽奖
        ZwLotteryActivityRef.value.onOpen(state);
    }
};
const change = index => {
    state.mutual = index;
    state.chooseName = '';
    state.page = constants.mutual_type[state.mutual];
    state.id = '';
    rowId.value = '';
    state.url = '';
    // 分类分组默认选中第一次
    if (state.mutual == 4) {
        state.id = props.category?.[0]?.id;
    }
    state.openimg = '';
    if ([1, 5, 4, '', 7, 13, 18].includes(state.mutual)) {
        getUrl();
    } else {
        emit('sendParam', state);
    }
};
const selectGroup = val => {
    getUrl();
    emit('sendParam', state);
};

const imgChangeHandler = ({ imgUrl, msg }) => {
    state.openimg = imgUrl || '';
    emit('sendParam', state);
    if (msg) {
        ElMessage.warning(msg);
    }
};
// 拼接跳转路径
const getUrl = () => {
    if (state.mutual == 1 || state.mutual == 4 || state.mutual == 5 || state.mutual == 13 || state.mutual == 18) {
        state.url = mutualType[state.mutual];
    } else if (state.mutual == 2 || state.mutual == 3) {
        state.url = mutualType[state.mutual] + state.id;
    } else if (state.mutual == 6) {
        state.url = mutualType[state.mutual] + state.id + '&shopId=' + storage.get('ZW-SHOPID');
    } else if (state.mutual == 8 || state.mutual == 9) {
        state.url = mutualType[state.mutual] + state.id + '&activityId=' + state.activityId;
    } else if (state.mutual == 10) {
        state.url = mutualType[state.mutual] + state.activityId + '&shopId=' + storage.get('ZW-SHOPID');
    } else if (state.mutual == 11) {
        state.url = mutualType[state.mutual] + state.id;
    }
    emit('sendParam', state);
};
/**微页面取消 */
const cancel = () => {
    open.value = false;
    pageRef.value.init();
};
/**添加微页面 */
const submit = param => {
    if (!param.id) {
        ElMessage.warning('请选择商品');
        return;
    }
    state.id = param.id;
    state.chooseName = param.name;
    getUrl();
    pageRef.value.init();
    open.value = false;
};
/**选择秒杀活动 */
const getSeckill = param => {
    rowId.value = param.id;
    state.id = param.goodsId;
    state.chooseName = param.activityName;
    Object.assign(state, { activityId: param.id });
    getUrl();
};
/**选择拼团活动 */
const getGroup = param => {
    rowId.value = param.id;
    state.id = param.goodsId;
    state.chooseName = param.activityName;
    Object.assign(state, { activityId: param.id });
    getUrl();
};
/** 抽奖活动*/
const getLottery = param => {
    state.id = param.id;
    state.chooseName = param.activityName;
    Object.assign(state, { activityId: param.id });
    getUrl();
};
/**满减活动 */
const getSelected = (param, index) => {
    state.id = param.id;
    state.chooseName = param.activityName;
    getUrl();
};
/**优惠券取消 */
// const couponCancel = () => {
//     couponOpen.value = false;
//     couponRef.value.init();
// };
/**添加优惠券 */
const couponSubmit = param => {
    state.id = param.id;
    state.chooseName = param.couponName;
    getUrl();
    // couponRef.value.init();
    // couponOpen.value = false;
};
/**添加商品 */
const goodssubmit = param => {
    state.id = param.id;
    state.chooseName = param.goodsName;
    getUrl();
};
watch(
    () => [props.row, props.category, props.typeList],
    val => {
        val[0].mutual = isNotEmpty(val[0].mutual) ? Number(val[0].mutual) : '';
        Object.assign(state, val[0]);
        let ids = props.category.map(item => item.id);
        // 兼容历史数据,默认初始化第一个
        if (state.mutual == 4) {
            if (!props.category.length) {
                //分组全部删除，id置空
                state.id = '';
            } else if (!state.id) {
                // 兼容历史数据,默认初始化第一个
                state.id = props.category?.[0]?.id;
            } else {
                // 已选分组被删除，默认第一个
                if (!ids.includes(state.id)) {
                    state.id = props.category?.[0]?.id;
                }
            }
        }
    },
    { immediate: true, deep: true }
);
</script>
<style lang="scss" scoped>
.tips {
    margin: 10px 0 0 0;
    font-size: 12px;
    font-weight: 400;
    color: #969696;
    line-height: 17px;
}
.label_hide :deep(.el-form-item__label-wrap) > .el-form-item__label {
    opacity: 0;
}
.btnText-hidden {
    cursor: pointer;
    max-width: 224px;
    padding: 0px 15px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    font-size: inherit;
    font-weight: 500;
    color: #606266;
}
</style>
